import ui_mainw
# import PySide6.sip
from PySide6.QtWidgets import QStyle
from PySide6.QtSql import QSqlQueryModel
from PySide6.QtWidgets import QAbstractItemView, QMainWindow, QApplication, QMessageBox, QCheckBox, QHBoxLayout
from PySide6.QtWidgets import QFileDialog
from PySide6 import QtWidgets
from PySide6.QtCore import QAbstractTableModel, QModelIndex
from PySide6.QtCore import QDateTime, QTime, Qt
from PySide6.QtSql import QSqlQuery, QSqlTableModel
import os
import csv
import config_json
from PySide6 import QtSql
import openpyxl
from ComboBoxDelegateQt import ComboBoxDelegateQt as EditDelegateQt
import getpath
import json
import subprocess
import bjItems
import sqlalchemy
import mydb
from objectModel import ObjectListTableViewQt, ObjectListTableModelQt
from DateTimeEditDelegateQt import DateTimeEditDelegateQt
import logging
# from EditDelegateQt import EditDelegateQt
# The model is read-only by default. To make it read-write, you must subclass it and reimplement setData() and flags()
def datetime_str(d2):
    return "%04d-%02d-%02d %02d:%02d:%02d" % (d2.year,d2.month,d2.day,d2.hour,d2.minute,d2.second)
class MyModel(ObjectListTableModelQt):
    def __init__(self, objects, properties, isRowObjects, isDynamic):
        super().__init__(objects,properties, isRowObjects, isDynamic)
        self.beizhu = {}

    def setQuery(self, cmd):
        self.beizhu = {}
        super().setQuery(cmd)
        pass

    def setData(self, index, value, role=Qt.EditRole):
        print("setData")
        cols = self.columnCount(QModelIndex())
        row = index.row()
        column = index.column()
        if column == cols-1 and role == Qt.EditRole:
            self.beizhu[row] = value
            self.dataChanged.emit(index, index, [role])  # todo here
            return True
        return super().setData(index, value, role)

    def flags(self, index):
        # print("flags")
        fl = super().flags(index)
        if index.column() == self.columnCount(QModelIndex())-1:
            fl |= Qt.ItemFlag.ItemIsEditable
        # print(dir(self))
        # print(index.column(),self.columnCount( QModelIndex()))
        return fl

    def columnCount(self, parent):
        count = super().columnCount(parent)
        return count+1

    def data(self, index, role):
        cols = self.columnCount(QModelIndex())
        row = index.row()
        column = index.column()
        if role == Qt.EditRole or role == Qt.DisplayRole:
            if column == cols-1:
                try:
                    return self.beizhu[row]
                except KeyError:
                    return None
        return super().data(index, role)


def inList(one, l):
    for i in range(len(l)):
        if one == l[i]:
            return i
    return -1


class Mydialect(csv.Dialect):
    delimiter = ","
    escapechar = '\\'
    doublequote = True
    skipinitialspace = True
    lineterminator = '\r\n'
    quoting = csv.QUOTE_ALL
    quotechar = '"'


def timestr():
    db = QDateTime.currentDateTime()
    db_str = db.toString("yyyy_MM_dd_hh_mm_ss")
    return db_str


def is_float(a_string):
    try:
        float(a_string)
        return True
    except TypeError:
        return False
    except ValueError:
        return False


class DoubleDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self, painter, option, index):
        # 注意，此时index是logicIndex（model坐标），我们可以通过拖拽表头项交换列来测试
        # QStyle会根据option的属性进行绘制，我们也可以不使用QStyle的规则，完全自定义
        opt = option
        # 去掉焦点 setFocusPolicy(Qt::NoFocus);
        # opt.state &= ~QStyle.State_HasFocus
        # 参照源码实现了自己的initStyleOption
        # self.initMyStyleOption(opt, index)
        value = index.model().data(index, Qt.EditRole)
        if is_float(value):
            opt.text = "%0.6f" % value
        else:
            opt.text = value
        widget = opt.widget
        if widget:
            style = widget.style()
        else:
            style = QApplication.style()
        style.drawControl(QStyle.CE_ItemViewItem, opt, painter, widget)


class MainW(QMainWindow):
    ui = ui_mainw.Ui_MainWindow()

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.db=None
        self.connection = None
        self.ui.setupUi(self)
        self.ui.spinBox_day.setValue(200)
        config_json.read_setting()
        if config_json.setting2.value("sblx") not in config_json.setting["sblx_list"]:
            config_json.setting2.setValue(
                "sblx", config_json.setting["sblx_list"][0])
        # self.setWindowTitle("纳克气体仪器数据上报")
        self.setWindowTitle(config_json.setting2.value("sblx"))
        self.set_database()
        self.h = QHBoxLayout(self.ui.groupBox)
        self.ncol = 0
        self.m_doubleDeleget = DoubleDelegate()
        self.m_comboDelegate = EditDelegateQt(config_json.setting["beizhu"])
        self.dateDelegate=DateTimeEditDelegateQt()#
        # self.ui.spinBox_month.valueChanged.connect(self.month_change)
        self.ui.spinBox_day.valueChanged.connect(self.day_change)
        self.model = QSqlQueryModel(self)
        # self.model.setQuery("select * from result where 分析时间 between '"+db_str+"' and '"+de_str+"'");
        # self.old=-1
        self.objects = []  # self.db.getDataDays(200)
        # obj=objects[0]
        # print(dir(obj))
        self.properties = [
            {'attr': "SampleId",'visible':True,  'header': "id",'text': "%c"      },
            {'attr': "SampleName",'visible':True,  'header': "name"},
            {'attr': "SampleWeight",'visible':True,  'header': "weight"},
            {'attr': "Content10",'visible':True,       'header': "Content10"},
            {'attr': "Content20",'visible':True,       'header': "Content20"},
            {'attr': "Content30",'visible':True,       'header': "Content30"},
            {'attr': "Content40",'visible':True,       'header': "Content40"},
            {'attr': "Content50",'visible':True,       'header': "Content50",      'mode': "Read Only"},
            {'attr': "Content60",'visible':True,       'header': "Content60",      'mode': "Read Only"},
        ]
        self.setHeader()
        self.model = ObjectListTableModelQt(
            self.objects, self.properties, isRowObjects=True, isDynamic=True)
        self.ui_tableView = ObjectListTableViewQt(self.model)
        vbox = QtWidgets.QVBoxLayout(self.ui.groupBox_2)
        vbox.addWidget(self.ui_tableView)

        # self.ui_tableView.setModel(self.model)
        self.ui_tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        # self.ui.dateTimeEdit_begin.dateTimeChanged.connect(self.begin_change)
        # self.ui.dateTimeEdit_end.dateTimeChanged.connect(self.end_change)
        # self.ui.menuedit.menuAction().setVisible(False);
        # self.ui_tableView.clicked.connect(self.row_clicked)
        self.ui.btnSelect.clicked.connect(self.select)
        self.ui.btnUnselect.clicked.connect(self.unselect)
        self.ui.btnSelect.setText("↓")
        self.ui.btnUnselect.setText("↑")
        self.ui.btnClear.clicked.connect(self.clear)
        self.ui.btnLims.clicked.connect(self.lims)
        self.ids = []
        self.objects2=[]
        self.model2 = ObjectListTableModelQt(self.objects2, self.properties, isRowObjects=True, isDynamic=True)
        self.ui_tableView_report = ObjectListTableViewQt(self.model2)
        vbox = QtWidgets.QVBoxLayout(self.ui.groupBox_3)
        vbox.addWidget(self.ui_tableView_report)

        self.ui.actionsetting.triggered.connect(self.setting)
        self.ui.actionffbh.triggered.connect(self.set_ffbh)
        self.ui.action_exit.triggered.connect(self.exit_app)
        self.ui.actionsave_as.triggered.connect(self.save_as)
        self.ui.actionsyy.triggered.connect(self.set_syy)

        # for i in range(len(config_json.setting["fields"])):
        #     f = config_json.setting["fields"][i]
        #     c = QCheckBox(f["name"])
        #     c.setChecked(f["used"])
        #     h.addWidget(c)
        #     c.pressed.connect(
        #         lambda val=i: self.field_click(val)
        #     )
        # self.lc=False
        # self.ls=True
        # self.hc=True
        # self.hs=False
        # self.genFieldStr()
        # self.model2.setQuery("select " + self.fieldStr + " from result where 分析时间 in " + self.idstr())
        self.ui_tableView_report.setModel(self.model2)
        self.ui_tableView_report.setSelectionBehavior(
            QAbstractItemView.SelectRows)

        if config_json.setting2.value("sblx") == "cs":
            ff = config_json.setting["ffbh_cs"]
        else:
            ff = config_json.setting["ffbh_onh"]
        syy = config_json.setting["syy"]
        # ysry = config_json.setting["ysry"]
        yqbh = config_json.setting2.value("yqbh")
        print(ff, syy, yqbh)
        for i in ff:
            self.ui.cmb_ffbh.addItem(i)
        for i in syy:
            self.ui.cmb_syy.addItem(i)
            self.ui.cmb_syyqm.addItem(i)
            self.ui.cmb_ysry.addItem(i)
        self.ui.lineEdit_yqbh.setText(yqbh)
        self.ui.cmb_ffbh.setCurrentIndex(
            config_json.setting["current"]["ffbh"])
        self.ui.cmb_syy.setCurrentIndex(config_json.setting["current"]["syy"])
        self.ui.cmb_ysry.setCurrentIndex(
            config_json.setting["current"]["ysry"])
        self.ui.cmb_syyqm.setCurrentIndex(
            config_json.setting["current"]["syyqm"])
        self.ui.cmb_syy.currentIndexChanged[int].connect(self.syy_change)
        self.ui.cmb_ysry.currentIndexChanged[int].connect(self.ysry_change)
        self.ui.cmb_ffbh.currentIndexChanged[int].connect(self.ffbh_change)
        self.ui.cmb_syyqm.currentIndexChanged[int].connect(self.syyqm_change)
        self.ui.pushButton_query.clicked.connect(self.query)
        self.ui.action.triggered.connect(self.beizhu)
        self.resetItems()
        self.ui.action_version.triggered.connect(self.version)
        self.ui.action_upgrade.triggered.connect(self.upgrade)
        self.ui.action_sync.triggered.connect(self.sync)
        self.ui.groupBox_2.setTitle("")
        self.ui.groupBox_3.setTitle("")
    def setHeader(self):
        if config_json.setting2.value("sblx") == "cs":
            items = config_json.setting["fields_cs"]
        else:
            items = config_json.setting["fields_onh"]
        for one in items:
            for p in self.properties:
                print("===========")
                print(one,p)
                if p['attr']==one["field"]:
                    p['header']=one["name"]
                print(p)
        print(self.properties)
    def sync(self):
        src_path = r"""\\10.0.114.230\化学分析室\仪器采集\reports\report_import"""
        file_name = os.path.join(src_path, "setting.json")
        print('Reading %s...' % file_name)
        new_setting = json.load(open(file_name, encoding="utf-8"))
        # ffbh_cs
        (left, right) = bjItems.bjitems(
            config_json.setting["ffbh_cs"], new_setting["ffbh_cs"])
        print(left, right)
        for one in right:
            config_json.setting["ffbh_cs"].append(one)
        for one in left:
            new_setting["ffbh_cs"].append(one)
        # ffbh_onh
        (left, right) = bjItems.bjitems(
            config_json.setting["ffbh_onh"], new_setting["ffbh_onh"])
        print(left, right)
        for one in right:
            config_json.setting["ffbh_onh"].append(one)
        for one in left:
            new_setting["ffbh_onh"].append(one)
        # syy
        (left, right) = bjItems.bjitems(
            config_json.setting["syy"], new_setting["syy"])
        print(left, right)
        for one in right:
            config_json.setting["syy"].append(one)
        for one in left:
            new_setting["syy"].append(one)
        # output
        with open(file_name, 'w', encoding="utf-8") as set_file:
            json.dump(new_setting, set_file, indent=4)

    def version(self):
        # from version import version
        # ,QMessageBox.Ok ,QMessageBox.Ok)
        QMessageBox.about(self, '版本号', config_json.setting["version"])

    def upgrade(self):
        src_path = r"""\\10.0.114.230\化学分析室\仪器采集\reports\report"""
        file_name = os.path.join(src_path, "setting.json")
        print('Reading %s...' % file_name)
        new_setting = json.load(open(file_name, encoding="utf-8"))
        new_version = int(new_setting["version"])
        version = int(config_json.setting["version"])
        if new_version > version:
            print("has new_version", new_version)
            r = QMessageBox.question(
                self, '升级', '是否升级', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if r == QMessageBox.Yes:
                print("yes")
                self.close()
                args = ["xcopy.exe", "/Y", src_path, getpath.getpath()]
                subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=True)
            else:
                print("no")
        else:
            print("not new_version", new_version)
        pass

    def clearLayout(self, layout):
        while True:
            child = layout.takeAt(0)
            print(child)
            if child == None:
                break
            else:
                print(dir(child))
                child.widget().deleteLater()

    def resetItems(self):
        # print(dir(self.h))
        self.clearLayout(self.h)
        items = None
        if config_json.setting2.value("sblx") == "cs":
            items = config_json.setting["fields_cs"]
        else:
            items = config_json.setting["fields_onh"]
        for i in range(len(items)):
            f = items[i]
            c = QCheckBox(f["name"])
            c.setChecked(f["used"])
            # print(c,dir(c))
            self.h.addWidget(c)
            c.pressed.connect(
                lambda val=i: self.field_click(val)
            )
        self.genFieldStr()
        self.refresh_grid()
    #     self.model2.rowsAboutToBeRemoved.connect(self.toremove)
    # def toremove(self,p,f,l):
    #     print("toremove==========================")
    #     print(p,f,l)

    def beizhu(self):
        from dlgbeizhu import Dlgbeizhu
        d = Dlgbeizhu()
        r = d.exec()
        if r == 1:
            # self.refresh_ffbh()
            # self.m_comboDelegate=EditDelegateQt(config_json.setting["beizhu"])
            # maybe because m_comboDelegate is already used by talbleview can not change here;error here
            pass
        else:
            pass

    def set_database(self):
        if self.db==None:
            self.db=mydb.MyDb()
        else:
            print("init_db==")
            self.db.init_db()

    def ysry_change(self, at):
        config_json.setting["current"]["ysry"] = at

    def syyqm_change(self, at):
        config_json.setting["current"]["syyqm"] = at

    def ffbh_change(self, at):
        config_json.setting["current"]["ffbh"] = at

    def syy_change(self, at):
        self.ui.cmb_syyqm.setCurrentIndex(at)
        config_json.setting["current"]["syy"] = at

    def closeEvent(self, event):
        config_json.write_setting()
        event.accept()

    # {
    #     if (maybeSave()) {
    #         writeSettings();
    #         event->accept();
    #     } else {
    #         event->ignore();
    #     }
    # }
    def refresh_ffbh(self):
        if config_json.setting2.value("sblx") == "cs":
            ff = config_json.setting["ffbh_cs"]
        else:
            ff = config_json.setting["ffbh_onh"]
        self.ui.cmb_ffbh.clear()
        for i in ff:
            self.ui.cmb_ffbh.addItem(i)
        self.ui.cmb_ffbh.setCurrentIndex(
            config_json.setting["current"]["ffbh"])

    def refresh_syy(self):
        ff = config_json.setting["syy"]
        self.ui.cmb_syy.clear()
        self.ui.cmb_syyqm.clear()
        self.ui.cmb_ysry.clear()
        for i in ff:
            self.ui.cmb_syy.addItem(i)
            self.ui.cmb_syyqm.addItem(i)
            self.ui.cmb_ysry.addItem(i)
        self.ui.cmb_syy.setCurrentIndex(config_json.setting["current"]["syy"])
        self.ui.cmb_ysry.setCurrentIndex(
            config_json.setting["current"]["ysry"])
        self.ui.cmb_syyqm.setCurrentIndex(
            config_json.setting["current"]["syyqm"])

    def genFieldStr(self):
        self.ncol = 3
        r = "SUBSTR(Sampleid,0,20) as 分析时间,samplename as sampleid,sampleweight as m"
        self.heads = ["分析时间", "sampleid", "m"]
        if config_json.setting2.value("sblx") == "cs":
            items = config_json.setting["fields_cs"]
        else:
            items = config_json.setting["fields_onh"]

        for f in items:
            if f["used"]:
                r += "," + f["field"] + " as " + f["name"]
                self.ncol += 1
                self.heads.append(f["name"])
        self.fieldStr = r

    def field_click(self, i):
        print(i)
        if config_json.setting2.value("sblx") == "cs":
            items = config_json.setting["fields_cs"]
        else:
            items = config_json.setting["fields_onh"]
        items[i]["used"] = not items[i]["used"]
        # print(config_json.setting["fields"])
        # self.genFieldStr()
        self.refresh_grid()

    def refresh_grid(self):
        self.refresh_grid1()
        self.refresh_grid2()

    def refresh_grid1(self):
        # if not self.db.inited:
        #     return
        # n=self.ui.spinBox_day.value()
        # self.objects=self.db.getDataDays(n)
        self.model.setObjects(self.objects)
        self.ui_tableView.setModel(self.model)
        self.ui_tableView.setColumnWidth(0, 150)
        # self.ui_tableView.setItemDelegateForColumn(0,self.dateDelegate)
        # print("col", self.ncol)
        # self.ncol=self.model.columnCount()
        # for i in range(3, self.ncol):
        #     print(i, 'setIemtDelegate')
        #     self.ui_tableView.setItemDelegateForColumn(i, self.m_doubleDeleget)

    def refresh_grid2(self):
        # logging.info(self.ids)
        # if not self.db.inited:
        #     return
        # n=self.ui.spinBox_day.value()
        # self.objects2=self.db.getDataIds(self.ids)
        # if len(self.objects2)>0:
        #     o=self.objects2[0]

        self.model2.setObjects(self.objects2)
        self.ui_tableView_report.setModel(self.model2)
        self.ui_tableView_report.setColumnWidth(0, 150)
        # self.model2.setHeaderData(self.ncol, Qt.Horizontal, "备注")
        # self.ui_tableView_report.setItemDelegateForColumn(
        #     self.ncol, self.m_comboDelegate)
        # for i in range(3, self.ncol):
        #     print(i, 'setIemtDelegate')
        #     self.model2.setHeaderData(i, Qt.Horizontal, self.heads[i])
        #     self.ui_tableView_report.setItemDelegateForColumn(
        #         i, self.m_doubleDeleget)

    def exit_app(self):
        pass
        # config_json.write_setting()
        self.close()

    def set_ffbh(self):
        from dlgffbh2 import Dlgffbh
        d = Dlgffbh()
        r = d.exec()
        if r == 1:
            self.refresh_ffbh()
        else:
            pass

    def set_syy(self):
        from dlgsyy2 import DlgSyy
        d = DlgSyy()
        r = d.exec()
        if r == 1:
            self.refresh_syy()
        else:
            pass

    def setting(self):
        # from todo import DlgTodo
        # d=DlgTodo()
        # d.exec()
        from dlgsetting import DlgSetting
        calculator = DlgSetting()
        r = calculator.exec()
        # print(r)s
        if r == 1:
            self.set_database()
            self.ui.lineEdit_yqbh.setText(config_json.setting["yqbh"])
            self.setWindowTitle(config_json.setting["sblx"])
            self.resetItems()
        else:
            pass

    def checkBoth(self):
        if config_json.setting2.value("sblx") == "cs":
            items = config_json.setting["fields_cs"]
        else:
            items = config_json.setting["fields_onh"]
        name = []
        for f in items:
            if f["used"]:
                if (f["name"][-1] in name):
                    QMessageBox.information(self, "", "不能同时选择一个元素的两个通道")
                    return True
                else:
                    name.append(f["name"][-1])
        return False

    def lims(self):
        if self.checkBoth():
            return
        if self.ui.lineEdit_filename.text() == "":
            file_name = config_json.setting2.value("yqbh") + "_" + timestr()
        else:
            file_name = self.ui.lineEdit_filename.text()
        path = config_json.setting2.value("output_folder")
        filepath = os.path.join(path, file_name)
        self.output_xlsx(filepath)

    def save_as(self):
        FileDialog = QFileDialog(self)
        FileDirectory = FileDialog.getSaveFileName(self)  # 选择目录，返回选中的路径
        fn = FileDirectory[0]
        if fn != "":
            self.output_xlsx(fn)

    def rowcolToStr(self, row, col):
        a = range(65, 70)
        r = {}
        at = 0
        for i in a:
            r[at] = chr(i)
            at += 1
        return r[col]+str(row)
    def getObjectValue(self,obj,prop):
        if config_json.setting2.value("sblx") == "cs":
            items = config_json.setting["fields_cs"]
        else:
            items = config_json.setting["fields_onh"]
        for one in items:
            if one["name"]==prop:
                return getattr(obj,one["field"])
        return None
    def output_xlsx(self, filepath):

        n = self.model2.rowCount()
        if n == 0:
            return
        filepath = filepath + ".xlsx"
        # 1. 创建文件对象（指定文件名，模式，编码方式）a模式 为 下次写入在这次的下一行
        wb = openpyxl.Workbook()
        # 3. 构建列表头
        row = ["id", "m"]

        if config_json.setting2.value("sblx") == "cs":
            items = config_json.setting["fields_cs"]
        else:
            items = config_json.setting["fields_onh"]
        for f in items:
            if f["used"]:
                row.append(f["name"][-1])
        row.append("备注")
        row.append("time")

        ws = wb.active
        ws.append(row)
        # print(self.model2.beizhu)
        for row_idx in range(n):
            record = self.model2.getObjectRow(row_idx)
            row = [record.SampleName,
                   record.SampleWeight]
            for f in items:
                if f["used"]:
                    row.append(self.getObjectValue(record,f["name"]))
            row.append(record.SampleId)
            ws.append(row)
        ffbh = self.ui.cmb_ffbh.currentText()
        syy = self.ui.cmb_syy.currentText()
        ysry = self.ui.cmb_ysry.currentText()
        yqbh = self.ui.lineEdit_yqbh.text()
        syyqm = self.ui.cmb_syyqm.currentText()
        row = ["ffbh&" + ffbh, "", "", "", ""]
        ws.append(row)
        row = ["syy&" + syy, "", "", "", ""]
        ws.append(row)
        row = ["ysry&" + ysry, "", "", "", ""]
        ws.append(row)
        row = ["yqbh&" + yqbh, "", "", "", ""]
        ws.append(row)
        row = ["syyqm&" + syyqm, "", "", "", ""]
        ws.append(row)
        ws.column_dimensions['A'].width = 30.0
        # ws[self.rowcolToStr(n+1,3)].number_format = '0.000000'
        wb.save(filepath)
        self.ui.textEdit.insertPlainText(filepath + "\n")
        scrollbar = self.ui.textEdit.verticalScrollBar()
        scrollbar.setSliderPosition(scrollbar.maximum())


    # def idstr(self):
    #     r = "("
    #     for i in range(len(self.ids)):
    #         r += '"' + self.ids[i] + '"' + ","
    #     r = r[:-1]
    #     r += ")"
    #     print(r)
    #     return r

    def clear(self):
        self.ids = []
        self.refresh_grid2()
        # self.model2.setQuery("select " + self.fieldStr +
        #                      " from result where 分析时间 in " + self.idstr())
        # self.model2.beizhu = {}

    def unselect(self):
        # print("select")
        # print(self.ids)
        selections = self.ui_tableView_report.selectionModel()
        list1 = selections.selectedIndexes()
        objs = []
        for i in range(len(list1)):
            current = list1[i]
            if current.column() == 0:
                row = current.row()
                obj= self.model2.getObject(current)
                objs.append(obj)
        for obj in objs:
            self.objects.remove(obj)
            self.objects2.append(obj)
        self.refresh_grid()
    def select(self):
        # print("select")
        selections = self.ui_tableView.selectionModel()
        list1 = selections.selectedIndexes()
        objs=[]
        for i in range(len(list1)):
            current = list1[i]
            # print(current,dir(current))
            if current.column() == 0:
                obj = self.model.getObject(current)
                objs.append(obj)
        for obj in objs:
            self.objects.remove(obj)
            self.objects2.append(obj)
        self.refresh_grid()
    def day_change(self, v):
        pass
    def query(self):
        if not self.db.inited:
            return
        n=self.ui.spinBox_day.value()
        self.objects=self.db.getDataDays(n)
        self.objects2=[]
        self.refresh_grid()
        pass

if __name__ == "__main__":
    import sys
    a = QApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)
    w = MainW()
    w.show()
    sys.exit(a.exec())
        